package com.imufe.chemicalenterprisedangerwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imufe.chemicalenterprisedangerwarning.common.InfoCode;
import com.imufe.chemicalenterprisedangerwarning.entity.po.CheckPO;
import com.imufe.chemicalenterprisedangerwarning.entity.po.UserPO;
import com.imufe.chemicalenterprisedangerwarning.entity.query.CheckQuery;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.*;
import com.imufe.chemicalenterprisedangerwarning.exception.GlobalException;
import com.imufe.chemicalenterprisedangerwarning.mapper.CheckMapper;
import com.imufe.chemicalenterprisedangerwarning.mapper.RoleMapper;
import com.imufe.chemicalenterprisedangerwarning.mapper.UserRoleMapper;
import com.imufe.chemicalenterprisedangerwarning.security.UserSecurityService;
import com.imufe.chemicalenterprisedangerwarning.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imufe.chemicalenterprisedangerwarning.util.BeanUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.CustomSQLErrorCodesTranslation;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 检查表 服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-10-12
 */
@Log4j2
@Service
public class CheckServiceImpl extends ServiceImpl<CheckMapper, CheckPO> implements CheckService {

    @Autowired
    CheckMapper mapper;

    @Autowired
    UserService userService;

    @Autowired
    UserSecurityService userSecurityService;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    InspectionMethodService inspectionMethodService;

    @Override
    public CheckDetailedVO detailed(Long id) {
        CheckPO po = mapper.selectById(id);
        CheckDetailedVO detail = BeanUtils.copyPOJO(po, CheckDetailedVO.class);

        // TODO 这里要插入具体的添加细节
        // 检查人
        UserDetailedVO userDetail = userService.detailed(po.getUserId());
        detail.setUser(userDetail);

        // 检查形式
        InspectionMethodVO methodVO = inspectionMethodService.basic(po.getInspectionMethodId());
        detail.setInspectionMethod(methodVO);

        // 被检查企业
        EnterpriseVO enterpriseVO = enterpriseService.basic(po.getEnterpriseId());
        detail.setEnterprise(enterpriseVO);

        // 总分 TODO 这个还要等一等

        return detail;
    }

    @Override
    public CheckDetailedVO storage() throws GlobalException {

        // 寻找登录用户下的一条总分为空的一条记录
        Long userId = userSecurityService.getUserId();
        Long id = getStorage(userId);
        if(id == null)
            throw new GlobalException(InfoCode.NO_STAGING);
        return detailed(id);
    }

    @Override
    public CheckDetailedVO create(CheckQuery query) {

        // 删除掉该用户下的暂存记录
        Long userId = userSecurityService.getUserId();
        Long id = getStorage(userId);
        if(id != null)
            mapper.deleteById(id);

        CheckPO po = BeanUtils.copyPOJO(query, CheckPO.class);

        // 插入用户id
        po.setUserId(userId);

        // 插入检查机构
        po.setOrganization(userService.getUserOrganization(userId));

        // 插入检查主体
        Long roleId = userRoleMapper.selectRoleIdByUserId(userId);
        po.setType((byte) (roleId / 2));

        log.info(po);

        mapper.insert(po);

        return detailed(po.getId());
    }

    @Override
    public CheckDetailedVO save() {

        // 获取暂存记录
        Long userId = userSecurityService.getUserId();
        Long id = getStorage(userId);

        // TODO 将总分栏转为非空
        return detailed(id);
    }

    /**
     * 获取该用户下的暂存记录
     * @param userId 用户编号
     * @return 若存在返回检查编号，没有返回-1
     */
    private Long getStorage(Long userId) {
        LambdaQueryWrapper<CheckPO> qw = new LambdaQueryWrapper<>();
        qw
                .eq(CheckPO::getUserId, userId)
                .isNull(CheckPO::getTotalScore);

        CheckPO po = mapper.selectOne(qw);
        return po == null? null: po.getId();
    }
}
